Aula 34 - Rmarkdown avançado

Módulo 3: Apresentando suas análises

Carolina Musso

PROFESP, DEMSP, MS

Esta semana

Aula 33 - Rmarkdown avançado

  • Compilando apresentações em power-point e pdf

Aula 34 - Rmardown & Word

  • Edições específicas para .docx

Aula 35 - Fim do curso!

  • Aula síncrona!

Leituras para aprofundamento

Introdução

  • RMarkdown e suas aplicações na epidemiologia em saúde.
  • Muito tempo + softwares + profissionais

    • Maior possibilidade de erro

Documentos reprodutíveis

  • Economia de tempo

  • Não ficam atreladas a uma pessoa

Bons costumes: projetos

  • Ter um “pacotinho” reprodutível.

  • Pasta do projeto

    • com subpastas

      • caminho relativo, em vez de caminho absoluto.

Revisando: Estrutura do RMarkdown

  • Cabeçalho

  • Código

  • Texto

Opções no

  • Vimos no cabeçalho do chunk

  • Título no chunk

  • echo= ; message= ; warning= ; include=

  • eval=

  • results=

Chunk geral

  • Onde é possível fazer nele as configurações gerais
knitr::opts_chunk$set(echo = FALSE,
                      message  = FALSE, 
                      warning= FALSE)

Mais coisas no site do YiHui

Outros formatos…

  • HTML, PDF, Power Point, …

PPT

---
title: "Título"
subtitle: "Subtitle"
date: "22/10"
output:powerpoint_presentation:
---
---
title: "Título"
subtitle: "Subtitle"
date: "22/10"
output:
  powerpoint_presentation:
    reference_doc: template.pptx
---

HTML

  • Muitas funcionalidades

    • Dashboard, disponibilidade online, interatividade
---
title: "Untitled"
author: "Carolina Musso"
date: "2023-08-19"
output: html_document
---
MPG cyl disp hp rank_change rating cylinder mpg_plot
15.5 8 318.0 150
8 Cylinders
 
14.3 8 360.0 245
8 Cylinders
 
21.0 6 160.0 110
6 Cylinders
 
10.4 8 472.0 205
8 Cylinders
 
26.0 4 120.3 91
4 Cylinders
 
15.0 8 301.0 335
8 Cylinders
 
Data Source

Table Key

MPG: Miles Per Gallon
Cyl: Cylinders
disp: Displacement
hp: Horsepower
rank_change: Rank Change
rating: Rating

PDF

  • Compilar em .pdf -> LateX

  • Documentos técnicos, científicos e profissionais com formatação precisa.

  • Usa comandos de marcação para estruturar o conteúdo, como títulos, equações e tabelas.

  • Qualidade tipográfica consistente, sendo útil para equações complexas, índices e citações formatadas.

PDF

  • Precisamos instalar uma “engine”

  • No R: tinytex

    • instala pelo R
    • mais leve
pacman::p_load(tinytex)
tinytex::install_tinytex()

Um exemplo de relatório em PDF

---
knit: (function(inputFile, encoding) {
  rmarkdown::render(inputFile, encoding = encoding, output_file=paste0("Boletins/Boletim_Covid_View",
  format(as.Date(Sys.time()),'%d.%m.%y'), ".pdf"))})
output:
  pdf_document:
    fig_crop: false
    includes:
      in_header: Arquivos_auxiliares/preamble.tex
  word_document: default
mainfont: Arial
geometry: "left=3cm,right=3cm,top=2.5cm,bottom=2cm, headsep=1.5cm"
header-includes: |
  \usepackage{booktabs}
  \usepackage{float}
  \usepackage{newfloat}
  \usepackage{framed}
  \usepackage{color}
  \usepackage{float}
  \usepackage{fancyhdr}
  \usepackage[format=hang,font=small,labelfont=bf]{caption}
  \captionsetup{width=150mm}
  \usepackage{tabularx}
  \usepackage{array}
  \usepackage[brazil]{babel}
  \pagestyle{fancy}
  \fancyhead{}
  \fancyfoot{}
  \usepackage{graphicx}
  \usepackage{fancyhdr}
  \pagestyle{fancy}
  \setlength\headheight{25pt}
  \fancyhead[L]{\textbf{Gerência de Epidemiologia de Campo \\ Diretoria de Vigilância Epidemiológica }}
  \fancyhead[C]{\includegraphics[width = .2\textwidth]{Arquivos_auxiliares/gdf.png}} 
  \fancyhead[R]{\textbf{ Subsecretaria de Vigilância em Saúde\\ Secretaria de Saúde do Distrito Federal}}
  \lfoot{\today}\rfoot{Pag \thepage}
  \usepackage[default]{sourcesanspro}
  \usepackage[T1]{fontenc}
  \DeclareFloatingEnvironment[listname=loq, listname={Lisra de Quadros}]{quadro}
  \newenvironment{ctable}{\comicfont }{}
  \usepackage{enumitem,booktabs,cfr-lm}
  \usepackage[referable]{threeparttablex}
  \renewlist{tablenotes}{enumerate}{1}
  \makeatletter
  \setlist[tablenotes]{label=\tnote{\alph*},ref=\alph*,align=left,before={\footnotesize}}
  \makeatother
  \setlength\parindent{24pt}
  \usepackage{setspace}\doublespacing
  \usepackage{indentfirst}
  \usepackage{pdflscape}
  \newcommand{\blandscape}{\begin{landscape}}
  \newcommand{\elandscape}{\end{landscape}}
---

Templates

---
titulo: "Análise de Dados Categorizados"
subtitulo: "Trabalho Final"
aluno1:  "Carolina Musso 18/0047850"
aluno2: "Juliana Magalhães Rosa 18/0020935"
orientador: "Maria Teresa Leão"
ano: "1/2023"
referencias: auxiliar/referencias.bib
output: 
  bookdown::pdf_document2:
    template: auxiliar/template.tex
---

Templates

  • Arquivo .tex

%%%
% TIPO DE DOCUMENTO E PACOTES ----
%%%%
\documentclass[12pt, a4paper, twoside]{article}
\usepackage[left = 3cm, top = 3cm, right = 2cm, bottom = 2cm]{geometry}

$if(highlighting-macros)$
$highlighting-macros$
$endif$

\usepackage[brazilian]{babel}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{amsmath, amsfonts, amssymb}
\numberwithin{equation}{subsection} %subsection
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{colortbl}
\usepackage{titletoc,titlesec}
\usepackage{setspace}
\usepackage{indentfirst}
%\usepackage{natbib}
\usepackage[colorlinks=true, allcolors=black]{hyperref}
%\usepackage[brazilian,hyperpageref]{backref}
\usepackage[alf]{abntex2cite}
\usepackage{multirow} % https://www.ctan.org/pkg/multirow
%\\usepackage{float} % https://www.ctan.org/pkg/float
\usepackage{booktabs} % https://www.ctan.org/pkg/booktabs
\usepackage{enumitem} % https://www.ctan.org/pkg/enumitem
\usepackage{quoting} % https://www.ctan.org/pkg/quoting
\usepackage{epigraph}
\usepackage{subfigure}
\usepackage{anyfontsize}
\usepackage{caption}
\usepackage{adjustbox}
\usepackage{bm}
\usepackage{floatrow}
\floatsetup[figure]{capposition=bottom}
\floatsetup[table]{capposition=top}




\raggedbottom % https://latexref.xyz/_005craggedbottom.html


% COMANDOS -----
%%%%

\newtheorem{teo}{Teorema}[section]
\newtheorem{lema}[teo]{Lema}
\newtheorem{cor}[teo]{Corolário}
\newtheorem{prop}[teo]{Proposição}
\newtheorem{defi}{Definição}
\newtheorem{exem}{Exemplo}

\newcommand{\titulo}{$titulo$ \\ $subtitulo$}
\newcommand{\autora}{$aluno1$}
\newcommand{\autorb}{$aluno2$}
\newcommand{\autorc}{$aluno3$}
\newcommand{\autord}{$aluno4$}
\newcommand{\orientador}{ $orientador$ }
\usepackage[labelsep=period,labelfont=bf
]{caption}




\pagestyle{fancy}
\fancyhf{}
%\renewcommand{\headrulewidth}{0pt}
\setlength{\headheight}{16pt}
%C - Centro, L - Esquerda, R - Direita, O - impar, E - par
\fancyhead[RO, LE]{\thepage}
\renewcommand{\sectionmark}[1]{\markboth{#1}{}}

\titlecontents{section}[0cm]{}{\bf\thecontentslabel\ }{}{\titlerule*[.75pc]{.}\contentspage}
\titlecontents{subsection}[0.75cm]{}{\thecontentslabel\ }{}{\titlerule*[.75pc]{.}\contentspage}

\setcounter{secnumdepth}{3}
%\setcounter{tocdepth}{3}

\DeclareCaptionFormat{myformat}{ \centering \fontsize{10}{12}\selectfont#1#2#3}
\captionsetup{format=myformat}

%%%
%% INÍCIO DO DOCUMENTO 
%%%%%%

%% CAPA ----
\begin{document}
\begin{titlepage}
\begin{center}
\begin{figure}[h!]
    \centering
        \includegraphics[scale = 0.8]{../img/unb.png}
    \label{fig:unb}
\end{figure}
{\bf Universidade de Brasília \\
\bf Instituto de Exatas \\
\bf Departamento de Estatística}
\vspace{5cm}

\setcounter{page}{0}
\null
\Large
\textbf{\titulo}
\vspace{2.5cm}

\small
\vspace{0.2cm}
\textbf{\autora}\\
\textbf{\autorb}\\
\textbf{\autorc}\\
\textbf{\autord}\\

\vspace{1.5cm}
\small
Professor(a): \orientador \\
\end{center}



\vspace{5cm}

\begin{center}
{\bf{Brasília} \\ }
\bf{$ano$}
\end{center}
\end{titlepage}



\newpage

\pagenumbering{arabic}
\setcounter{page}{2}
\onehalfspacing




\setlength{\parindent}{1.5cm}
\setlength{\parskip}{0.2cm}
\setlength{\intextsep}{0.5cm}

\titlespacing*{\section}{0cm}{0cm}{0.5cm}
\titlespacing*{\subsection}{0cm}{0.5cm}{0.5cm}
\titlespacing*{\subsubsection}{0cm}{0.5cm}{0.5cm}
\titlespacing*{\paragraph}{0cm}{0.5cm}{0.5cm}

\titleformat{\paragraph}
{\normalfont\normalsize\bfseries}{\theparagraph}{1em}{}

\pagenumbering{arabic}
\setcounter{page}{3}

\fancyhead[RE, LO]{\nouppercase{\emph\leftmark}}
%\fancyfoot[C]{Departamento de Estatística}

% SUMÁRIO
%%%

\tableofcontents

\newpage


% CONTEÚDO (AS SEÇÕES SAO SEPARADAS NO RMARKDOWN) ---
%%%


$body$


%% CRONOGRAMA ----
%%%



%% REFERÊNCIAS ----
\newpage
\bibliography{$referencias$}


\end{document}

Templates

Outras formas de apresentação

Officer

my_pres <- read_pptx() 
layout_summary(my_pres)
             layout       master
1       Title Slide Office Theme
2 Title and Content Office Theme
3    Section Header Office Theme
4       Two Content Office Theme
5        Comparison Office Theme
6        Title Only Office Theme
7             Blank Office Theme
my_pres <- my_pres %>% 
  add_slide(layout = "Title and Content", master = "Office Theme") %>% 
  ph_with(value = c("Table cars"),
          location = ph_location_type(type = "title")) %>% 
  ph_with(value = c("Nota , fontes ..."),
          location = ph_location_type(type = "ftr")) %>% 
  ph_with(value = stri_rand_lipsum(1, start_lipsum = TRUE),
          location = ph_location_type(type = "body"), index=1) 


print(my_pres, target = "Example.pptx") %>% 
  invisible()

Extensões

Rmd

qmd

Obrigada!